<?php

namespace app\admin\controller;

use think\Controller;

class Index extends Controller
{
    //重复登录过滤
    public function initialize()
    {
        //session里有id（即登录过），则直接跳转后台首页
        if (session('?admin.id')){
            $this->redirect('admin/home/index');
        }
    }

    //后台登录
    public function login()
    {
        //接收数据
        if (request()->isAjax()){
            $data = [
                'admin_username' => input('post.admin_username'),
                'admin_password' => input('post.admin_password'),
                'verify' => input('post.verify')
            ];
            //将模型里校验的结果返回给$result
            $result = model('Admin')->login($data);
            if ($result == 1){
                $this->success('登录成功！','admin/home/index');
            }else{
                $this->error($result);
            }
        }
        return view();
    }

    //注册
    public function register()
    {
        if (request()->isAjax()){
            $data = [
                'admin_username' => input('post.admin_username'),
                'admin_password' => input('post.admin_password'),
                'conpass' => input('post.conpass'),
                'admin_nickname' => input('post.admin_nickname'),
                'admin_email' => input('post.admin_email'),
            ];
            $result = model('Admin')->register($data);
            if ($result == 1){
                $this->success('注册成功','admin/index/login');
            }else{
                $this->error($result);
            }
        }
        return view();
    }

    //忘记密码,发送验证码
    public function forget()
    {
        if (request()->isAjax()){
            $code = mt_rand(1000,9999);
            session('code',$code);
            $result = mailto(input('post.admin_email'),'重置密码验证码为：','您的重置密码验证码为：'.$code);
            if ($result){
                $this->success('验证码发送成功');
            }else{
                $this->error('验证码发送失败');
            }
        }
        return view();
    }

    //重置密码
    public function reset()
    {
        $data = [
          'code' => input('post.code'),
          'admin_email' => input('post.admin_email')
        ];
        $result = model('Admin')->reset($data);
        if ($result == 1){
            $this->success('密码重置成功，请去邮箱查看新密码','admin/index/login');
        }else{
            $this->error($result);
        }
    }

}
